'''
Descripttion: 
version: 
Author: Born
Date: 2020-02-16 14:03:51
LastEditors: Born
'''
from django.contrib import admin
from PeopleInfo.models import *
from reversion.admin import VersionAdmin
from django.db import transaction, connections
from xpinyin import Pinyin
from django.contrib import messages
from Dashboard.tasks import teacher_access_check_update
from import_export.admin import ImportExportModelAdmin, ExportActionModelAdmin, ImportExportMixin
from PeopleInfo.resources import *
from django.utils.html import mark_safe
import logging
from django.core.cache import cache
# Register your models here.


@admin.register(EntranceGuardList)
class EntranceGuardListAAdmin(ExportActionModelAdmin, ImportExportMixin, VersionAdmin):
    list_display = ['id', 'username', 'nickname', 'level', 'status', 'reason', 'source', 'lock', 'update_time', 'operate_str']
    search_fields = ['id', 'username', 'nickname', 'reason', 'remarks']
    list_filter = ['level', 'status', 'reason', 'source', 'lock', 'update_time']
    # radio_fields = {"status": admin.VERTICAL}
    change_list_template = "admin/change_list_recover.html"
    readonly_fields = ('create_time', 'update_time')

    @transaction.atomic
    def access_pass(self, request, queryset):
        try:
            queryset.update(status=1, reason='身体健康且未曾前往中高风险地区')
        except Exception as e:
            logging.error(e)
            self.message_user(request, '操作失败，请检查数据库：{}'.format(e), messages.ERROR)
        else:
            self.message_user(request, '操作成功', messages.INFO)
        # 修改数据后重定向url到新加数据页面
    access_pass.short_description = '将所选的 师生 的状态设置为准入'

    def access_no_pass(self, request, queryset):
        try:
            queryset.update(status=2, reason='不准入')
        except Exception as e:
            logging.error(e)
            self.message_user(request, '操作失败，请检查数据库：{}'.format(e), messages.ERROR)
        else:
            self.message_user(request, '操作成功', messages.INFO)
    access_no_pass.short_description = '将所选的 师生 的状态设置为不准入'

    actions = [access_pass, access_no_pass]

    resource_class = EntranceGuardListResource

    def save_model(self, request, obj, form, change):
        if obj.source in ('线下A类名单', '线下B类名单', '线下C类名单', '线下D类名单', '校领导名单'):
            obj.lock = True
        print("添加缓存")
        super().save_model(request, obj, form, change)
        # teacher_access_check_update(obj.username)

    def delete_model(self, request, obj):
        print("删除缓存")
        cache.delete_pattern('access_check_{}'.format(obj.username))
        super().delete_model(request, obj)

    def operate_str(self, obj):
        html = '<a href="/admin/illness_protection/dailysubmitinfonew?username={}">查看填报记录</a>'
        return mark_safe(html.format(obj.username))
    operate_str.short_description = '操作'


admin.site.site_header = '数据中心'
admin.site.site_title = '数据中心'
admin.site.index_title = '数据管理'
